<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      html,
      body {
        height: 100%;
      }
      * {
        margin: 0;
        padding: 0;
      }
      canvas {
        border: 1px solid black;
        margin: 0 auto;
        display: block;
      }
    </style>
  </head>
  <body>
    <canvas width="500" height="500">浏览器版本过低</canvas>
    <script>
      // 获取画布
      const canvas = document.querySelector('canvas');
      // 获取画笔
      const c = canvas.getContext('2d');
      const w = 500;
      const h = 500;
      let x = 100;
      let y = 100;
      let r = 30;
      let xSpeed = 1;
      let ySpeed = 2;
      setInterval(() => {
        // 清除画布
        c.clearRect(0, 0, w, h);
        if (x - r <= 0 || x + r >= w) {
          xSpeed = -xSpeed;
          console.log('x轴碰撞检测');
        }
        if (y - r <= 0 || y + r >= h) {
          ySpeed = -ySpeed;
          console.log('y轴碰撞检测');
        }
        x += xSpeed;
        y += ySpeed;
        drawCircle(x, y, r);
      }, 10);
      function drawCircle(x, y, r) {
        c.beginPath();
        c.arc(x, y, r, 0, Math.PI * 2);
        c.fillStyle = 'gold';
        c.fill();
        c.strokeStyle = 'gold';
        c.stroke();
        c.closePath();
      }
    </script>
  </body>
</html>
